#include <QHostAddress>
#include <QNetworkInterface>
#include <QMessageBox>
#include "opensession.h"
#include "ui_opensession.h"
#include "constants.h"
#include "Preferences/preferences.h"


OpenSession::OpenSession(QWidget *parent) : QDialog(parent), ui(new Ui::OpenSession)
{

        ui->setupUi(this);

        //load the username
        ui->lineEdit_user->setText(Preferences::getInstance()->getValue(Preferences::SETTING_DEFAULT_NAME).toString());

        ui->lineEdit_session->setText(ui->lineEdit_user->text() + "'s Session");

        //figure out the host ip (or guess a nice-ish one)
        QString host = "127.0.0.1";
        QList<QHostAddress> interfaceList = QNetworkInterface::allAddresses();

        for (int i = 1; i < interfaceList.length(); i++)
        {
                if (interfaceList.at(i).protocol() == QAbstractSocket::IPv4Protocol)
                {
                        host = interfaceList.at(i).toString();
                        break;
                }
        }

        ui->label_IP->setText(host);
        ui->label_port->setText(QString::number(DEFAULT_PORT));

        ui->lineEdit_session->setFocus();
}

OpenSession::~OpenSession()
{
        delete ui;
        ui = NULL;
}

QString OpenSession::getSessionName()
{
        return ui->lineEdit_session->text();
}

int OpenSession::getPort()
{
        return DEFAULT_PORT;
}

QString OpenSession::getUserName()
{
        return (ui->lineEdit_user->text());
}


void OpenSession::accept()
{
        if (ui->lineEdit_session->text().isEmpty())
        {
                QMessageBox::warning(this, "Invalid Session Information",
                                     "A valid session name is required to create "
                                     "a new session");

                ui->lineEdit_session->setFocus();
        }
        else if (ui->lineEdit_user->text().isEmpty())
        {
                QMessageBox::warning(this, "Invalid User Information",
                                     "A valid user name is required to create a new session");

                ui->lineEdit_user->setFocus();
        }
        else
        {
                //save the username and text colour
                Preferences::getInstance()->setValue(Preferences::SETTING_DEFAULT_NAME, ui->lineEdit_user->text());

                QDialog::accept();
        }
}

